package com.ming.attendance.interceptor;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.ming.attendance.exception.MyException;
import com.ming.attendance.utils.JWTUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.security.SignatureException;

import static jdk.nashorn.internal.runtime.regexp.joni.Config.log;

// 拦截器形式的token登陆检查
public class TokenCheckInterceptor implements HandlerInterceptor{

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		// TODO Auto-generated method stub

		// 从request中取token,如果没有,说明没有登录
		String token = request.getHeader("Authorization");
		if(StringUtils.isEmpty(token)){
			throw new MyException("token不能为空");
		}
		try {
			JWTUtils.verify(token);
		} catch (SignatureVerificationException e){
			log.println("无效签名! 错误-->"+e);
			return false;
		} catch (TokenExpiredException e) {
			log.println("token过期！ 错误 ->"+ e);
			return false;
		} catch (AlgorithmMismatchException e) {
			log.println("token算法不一致！ 错误 ->"+ e);
			return false;
		} catch (Exception e) {
			log.println("token无效！ 错误 ->"+ e);
			System.out.println(e);
			return false;
		}
		return true;
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub
		HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub
		HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
	}

}
